//
//  HomeHelper.m
//  HomeDecoration
//
//  Created by xalo on 16/2/26.
//  Copyright © 2016年 美家项目组. All rights reserved.
//

#import "HomeHelper.h"
#import "HomeModel.h"
@interface HomeHelper ()
@property (nonatomic,strong) NSMutableArray *modelArray;


@end

@implementation HomeHelper
//创建单例
+(id)sharedHomeHelper
{
    static HomeHelper *handle=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handle=[[HomeHelper alloc] init];
    });
    return handle;

}

//请求数据
//-(void)fetchDataWithUrl:(NSString *)url block:(Block)block
//{
//   dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
//                  NSArray *array=[NSArray arrayWithContentsOfURL:[NSURL URLWithString:url]];
//           for (NSDictionary *dic in array) {
//               HomeModel *homeModel=[[HomeModel alloc] init];
//               [homeModel setValuesForKeysWithDictionary:dic];
//               NSLog(@"%@123",homeModel);
//               [self.modelArray addObject:homeModel];
//           }
//           NSLog(@"%@456",self.modelArray);
//           dispatch_async(dispatch_get_main_queue(), ^{
//               block();
//           });
//
//
//    });
//    
//
//}
-(void)fetchDataWithUrl:(NSString *)url block:(Block)block
{

    dispatch_async(dispatch_get_global_queue(0, 0), ^{

    dispatch_async(dispatch_get_global_queue(0, 0), ^{        

        NSURL *Url=[NSURL URLWithString:url];
        NSURLSession *session=[NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask=[session dataTaskWithURL:Url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            NSArray *array=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            for (NSDictionary *dic in array) {
                HomeModel *homeModel=[[HomeModel alloc] init];
                [homeModel setValuesForKeysWithDictionary:dic];

                [self.modelArray addObject:homeModel];
            }

                
                [self.modelArray addObject:homeModel];
            }
           

            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
           
        }];
       
        [dataTask resume];

        

        
    });
    
    

    });

}

//返回model的方法
-(HomeModel *)returnHomeModelWithIndex:(NSInteger)index
{
    return self.modelArray[index];
}
//懒加载
-(NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray=[NSMutableArray array];


        NSLog(@"0000");

    }
    return _modelArray;

}
//返回数组个数
-(NSInteger)homeModelArrayCount
{
    return self.modelArray.count;

}


@end
